<template>
  <div class="container">
    <el-card class="card-box">
      <el-row v-if="pageParams.subjectID" class="breadcrumb">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <!-- <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item> -->
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{ pageParams.directoryName }}</el-breadcrumb-item>
          <el-breadcrumb-item>目录列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-row>

      <el-form ref="demoForm" :inline="true" :model="formInline" class="demo-form-inline">
        <el-row class="left" type="flex">
          <el-col>
            <el-form-item label="目录名称" prop="directoryName">
              <el-input v-model="formInline.directoryName" placeholder />
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="formInline.state" placeholder="请选择">
                <el-option
                  v-for="item in status"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            <!-- <template>{{status}}</template> -->
            </el-form-item>
            <el-form-item>
              <el-button @click="resetForm(formInline)">清除</el-button>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-button v-if="pageParams.subjectID" type="text" icon="el-icon-back" @click="$router.go(-1)">返回学科</el-button>
            <el-button type="success" icon="el-icon-edit" @click="hAdd">新增目录</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 警告 -->
      <el-alert v-if="alertText !== ''" :title="alertText" type="info" show-icon :closable="false" />
      <!-- 数据列表 -->
      <el-table
        :data="dataList"
        element-loading-text="给我一点时间"
        fit
        highlight-current-row
        style="width: 100%"
        border
      >
        <el-table-column align="center" label="序号" type="index" :index="indexChange" />
        <el-table-column align="center" label="所属学科">
          <template slot-scope="scope">
            <span>{{ scope.row.subjectName }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="目录名称">
          <template slot-scope="scope">
            <span>{{ scope.row.directoryName }}</span>
          </template>
        </el-table-column>

        <el-table-column align="center" label="创建者">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建日期">
          <template slot-scope="scope">
            <span>{{ time(scope.row.addDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="面试题数量">
          <template slot-scope="scope">
            <span>{{ scope.row.totals }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态">
          <template slot-scope="scope">
            <span v-if="scope.row.state==1">启用</span>
            <span v-else>禁用</span>
          </template>
        </el-table-column>
        <!-- 操作按钮 -->
        <el-table-column
          align="center"
          label="操作"
          width="280"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handleStatus(scope.row)">
              <span v-if="scope.row.state===0">启用</span>
              <span v-else>禁用</span>
            </el-button>
            <el-button
              type="text"
              size="mini"
              :disabled="scope.row.state === 1?true:false"
              @click="hEdit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              :disabled="scope.row.state === 1?true:false"
              @click="hDel(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- end -->
      <!-- 分页 -->
      <el-pagination
        background
        :current-page="pageParams.page"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <!-- end -->
    </el-card>
    <!-- 弹框 -->
    <el-dialog
      v-if="showDialog"
      :title="!isEdit? '新增目录':'修改目录'"
      :visible.sync="showDialog"
      width="30%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <addDirectorys
        ref="ruleForm"
        :is-edit="isEdit"
        :cur-row="curRow"
        :dir-name="dirName"
        @close="hClose"
        @success="hSuccess"
      />
    </el-dialog>
  </div>
</template>

<script>
// 格式化时间包
import moment from 'moment'
// 引入目录列表
import { list, remove, changeState } from '@/api/hmmm/directorys'
// 子组件
import addDirectorys from '../components/directorys-add.vue'
// 枚举
import { status } from '@/api/hmmm/constants'
export default {
  name: 'Directorys',
  components: { addDirectorys },
  data() {
    return {
      // 子组件校验的数据
      dirName: [],
      // 查询数据
      formInline: {
        directoryName: '',
        state: ''
      },
      isEdit: false, // 是否编辑
      showDialog: false, // 是否开启弹框
      alertText: '',
      total: 0, // 总条数
      pageParams: {
        page: 1, // 默认显示第几页
        pagesize: 10, // 默认显示多少条
        subjectID: '',
        directoryName: ''
      },
      dataList: [], // 存储目录列表
      curRow: {}, // 点击编辑传给子组件的数据
      status // 枚举
    }
  },
  created() {
    this.changeRoute()
    this.loadList()
  },
  methods: {
    changeRoute() {
      console.log(this.$route, 'route')
      this.pageParams.subjectID = this.$route.query.id
      this.pageParams.directoryName = this.$route.query.name
    },
    // 格式化时间
    time(addDate) {
      return moment(addDate).format('YYYY-MM-DD hh:mm:ss')
    },
    // 启用 禁用
    async handleStatus(row) {
      console.log(row.state, '测试')
      try {
        row.state ? (row.state = 0) : (row.state = 1)
        const res = await changeState({ id: row.id, state: row.state })
        this.loadList()
        this.$message.success('更改成功')
        console.log(res, '按钮')
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 每页显示信息条数
    handleSizeChange(val) {
      this.pageParams.pagesize = val
      this.loadList()
    },
    // 进入某一页
    handleCurrentChange(val) {
      this.pageParams.page = val
      this.loadList()
    },
    // 发送查询接口
    async searchList() {
      try {
        const res = await list(this.formInline)
        console.log(res, '查询')
        this.dataList = res.data.items
        this.total = res.data.counts
        this.alertText = `共 ${this.total} 条记录`
      } catch (error) {
        this.$message.error(error.message)
      }
    },
    // 查询
    onSubmit() {
      console.log('submit!')
      this.$refs.demoForm.validate(valid => {
        console.log(valid, '查询')
        if (valid) {
          this.searchList(this.pageParams)
        }
      })
    },

    // 清除
    resetForm(formName) {
      console.log(formName, '清除')
      // 1.清空表单
      this.$refs.demoForm.resetFields()
      // 2.重新渲染
      this.loadList()
    },
    // 获取目录列表
    async loadList() {
      try {
        let res = null
        if (this.pageParams.subjectID) {
          res = await list({
            page: this.pageParams.page,
            pagesize: this.pageParams.pagesize,
            subjectID: this.pageParams.subjectID
          })
        } else {
          // 1.发送请求
          res = await list(this.pageParams)
        }

        console.log(res, '目录列表')
        // 2.把需要校验的数据传给子组件
        this.dirName = res.data.items.map(item => {
          return { directoryName: item.directoryName, id: item.id }
        })
        console.log(this.dirName)
        // 3.存储目录列表
        this.dataList = res.data.items
        this.total = res.data.counts
        this.alertText = `共 ${this.total} 条记录`
      } catch (error) {
        // 4.提示错误信息
        this.$message.error(error.message)
      }
    },
    hClose() {
      this.showDialog = false
      this.$refs.ruleForm.ruleForm = {
        subjectName: '',
        directoryName: ''
      }
    },
    hSuccess() {
      this.showDialog = false
      this.loadList()
    },
    // 点击编辑
    hEdit(row) {
      this.curRow = { ...row }
      console.log(row, 'row')
      // 1.是否编辑
      this.isEdit = true
      // 2.开启弹框
      this.showDialog = true
      // 3.数据回填
      this.$nextTick(() => {
        this.$refs.ruleForm.fetchRow()
      })
    },
    // 点击新增
    hAdd() {
      // 1.关闭编辑
      this.isEdit = false
      // 2.开启弹框
      this.showDialog = true
    },
    // 点击删除
    hDel(id) {
      console.log(id, 'del')
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      })
        .then(() => {
          this.doDel(id)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 删除接口
    async doDel(id) {
      try {
        console.log(id)
        const res = await remove({ id })
        console.log(res, '删除')
        // 判断页数
        if (this.dataList.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page < 0) {
            this.pageParams.page = 1
          }
        }
        // 重新渲染页面
        this.loadList()
      } catch (error) {
        // 提示错误信息
        this.$message.error(error.message)
      }
    },

    // 分页索引
    indexChange(index) {
      return (this.pageParams.page - 1) * this.pageParams.pagesize + index + 1
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  padding: 10px;
  .card-box {
    padding: 20px;
    .breadcrumb {
      margin-bottom: 20px;
    }
    .el-breadcrumb__inner a,
    .el-breadcrumb__inner.is-link {
      color: #606266;
    }
    // .demo-form-inline {
    //   display: flex;
    //   justify-content: space-between;
    //   .right {
    //     display: flex;
    //   }
    // }
    .el-alert {
      margin-bottom: 15px;
    }
    .el-pagination {
      text-align: right;
      margin-top: 7px;
    }
  }
}
</style>
